package com.information.manage.maintenance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.information.manage.basic.mapper.StaffDetailMapper;
import com.information.manage.basic.model.entity.StaffDO;
import com.information.manage.basic.model.entity.StaffDetailDO;
import com.information.manage.basic.service.StaffService;
import com.information.manage.maintenance.mapper.*;
import com.information.manage.maintenance.model.dto.AdministratorPushDTO;
import com.information.manage.maintenance.model.dto.MaintenancePlanDTO;
import com.information.manage.maintenance.model.query.MaintPageQuery;
import com.information.manage.maintenance.model.query.StaffQuery;
import com.information.manage.maintenance.model.vo.DeviceType;
import com.information.manage.maintenance.model.vo.MaintenanceMenuVo;
import com.information.manage.maintenance.model.vo.MaintenancePlanVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.information.manage.maintenance.model.entity.Equipment;
import com.information.manage.maintenance.service.EquipmentService;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.information.manage.maintenance.common.general.StaticMapperResources.getMapper;

/**
 * (Equipment)表服务实现类
 *
 * @author makejava
 * @since 2025-01-22 22:10:08
 */
@Slf4j
@Service
public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper, Equipment> implements EquipmentService {

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private StaffService staffService;

    @Resource
    private StaffDetailMapper staffDetailMapper;

    //定时推送
    /**
     * 每天执行一次，每天晚上12点
     */
    @Scheduled(cron = "0 29 4 * * ?")
    public void scheduledPushTasks() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timer timer = new Timer();
        List<AdministratorPushDTO> equipmentName = super.list().stream()
                .map(equipment -> new AdministratorPushDTO(equipment.getEqid(), equipment.getEquipname()))
                .collect(Collectors.toList());
        String mailFrom = "javamail_lin@163.com";
        String subject = "维修计划";
        StringBuilder sendText = new StringBuilder();
        sendText.append("以下设备即将超期或已近超期，请及时前往系统查看并制定维修计划：");
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                log.info("{}","定时任务启动了");
                for (AdministratorPushDTO equip : equipmentName) {
                    Page<MaintenancePlanVo> execute = getMapper(equip.getEquipname()).execute(new Page<>(1, 1), equip.getEqid());
                    if(!execute.getRecords().isEmpty()){
                        sendText.append(equip.getEquipname());
                        sendText.append("；");
                    }
                }
                if(!Objects.equals(String.valueOf(sendText), "以下设备即将超期或已经超期，请及时前往系统查看并制定维修计划：")){
                    SimpleMailMessage mail = new SimpleMailMessage();
                    mail.setSubject(subject);
                    mail.setText(String.valueOf(sendText));
                    mail.setFrom(mailFrom);
                    mail.setTo("lin_19382116831@163.com");
                    mailSender.send(mail);
                }
            }
        }, 0, 1000 * 60 * 60 * 24);//0表示无延迟
    }

    @Override
    public List<MaintenanceMenuVo> getMenu() {
        List<Equipment> equipList = super.list();
        List<String> deviceNameList = equipList.stream()
                .map(Equipment::getEquipname)
                .distinct()
                .collect(Collectors.toList());
        List<MaintenanceMenuVo> menuVos = new ArrayList<>();
        deviceNameList.forEach(deviceName -> {
            MaintenanceMenuVo maintenanceMenuVo = new MaintenanceMenuVo();
            LambdaQueryWrapper<Equipment> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Equipment::getEquipname, deviceName);
            List<DeviceType> typeList = super.list(queryWrapper).stream()
                    .map(equipment -> new DeviceType(equipment.getEquiptype(),equipment.getEqid()))
                    .collect(Collectors.toList());
            maintenanceMenuVo.setDeviceName(deviceName);
            maintenanceMenuVo.setTypeList(typeList);
            menuVos.add(maintenanceMenuVo);
            menuVos.forEach(System.out::println);
        });
        return menuVos;
    }

    @Override
    public Page<MaintenancePlanVo> getMaintList(MaintPageQuery pageQuery) {
        LambdaQueryWrapper<Equipment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Equipment::getEqid,pageQuery.getEqId());
        String equipmentName = super.getOne(queryWrapper).getEquipname();
        return getMapper(equipmentName).execute(new Page<>(pageQuery.getCurPage(), pageQuery.getPageSize()),pageQuery.getEqId());
    }

    @Override
    public List<StaffQuery> getStaffList() {
        return staffService.list().stream()
                .map(staff ->new StaffQuery(staff.getName(),staff.getJobNumber()))
                .collect(Collectors.toList());
    }

    @Override
    public void sendMail(List<MaintenancePlanDTO> maint, Integer day,List<String> mailTo) {
        String mailFrom = "javamail_lin@163.com";
        String subject = "维修计划";
        StringBuilder sendText = new StringBuilder();
        sendText.append("以下设备即将超期或已近超期，请在")
                .append(day)
                .append("天后到相应地点进行检修。设备、类型、站区信息如下：");
        for (int i = 0; i < maint.size(); i++) {
            sendText.append(maint.get(i).getEquipmentName())
                    .append(" ")
                    .append(maint.get(i).getEquipmentType())
                    .append(" ")
                    .append(maint.get(i).getZhanquName());
                    if(i != maint.size()-1 ){
                        sendText.append("，");
                    }
        }
        for (String jobNum : mailTo) {
            LambdaQueryWrapper<StaffDO> queryWrapper = new LambdaQueryWrapper<>();
           queryWrapper.eq(StaffDO::getJobNumber,jobNum);
            LambdaQueryWrapper<StaffDetailDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StaffDetailDO::getId,staffService.getOne(queryWrapper).getStaffDetailId());
            String mailAddress = staffDetailMapper.selectOne(wrapper).getMail();
            SimpleMailMessage mail = new SimpleMailMessage();
            mail.setSubject(subject);
            mail.setText(String.valueOf(sendText));
            mail.setFrom(mailFrom);
            mail.setTo(mailAddress);
            mailSender.send(mail);
        }
    }
}




